using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OrderingSystem.Core.Interfaces;
using System.IO;

namespace OrderingSystem.API.Controllers
{
    [ApiController]
    [Route("file")]
    public class FileController : ControllerBase
    {
        private readonly IFileService _fileService;
        private readonly string _baseUploadPath;

        public FileController(IFileService fileService)
        {
            _fileService = fileService;
            _baseUploadPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file">文件</param>
        /// <param name="subDirectory">子目录（可选）</param>
        /// <returns>文件相对路径</returns>
        [HttpPost("upload")]
        [Authorize]
        public async Task<IActionResult> Upload(IFormFile file, [FromQuery] string subDirectory = "")
        {
            try
            {
                var filePath = await _fileService.UploadFileAsync(file, subDirectory);
                return Ok(new { filePath });
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { message = ex.Message });
            }
            catch (Exception)
            {
                return StatusCode(500, new { message = "文件上传失败" });
            }
        }

        /// <summary>
        /// 获取上传的文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns>文件内容</returns>
        [HttpGet("upload/{fileName}")]
        [AllowAnonymous]
        public IActionResult GetUploadedFile(string fileName)
        {
            try
            {
                var filePath = Path.Combine(_baseUploadPath, "upload", fileName);
                if (!System.IO.File.Exists(filePath))
                {
                    return NotFound(new { message = "文件不存在" });
                }

                var fileExtension = Path.GetExtension(fileName).ToLowerInvariant();
                var contentType = fileExtension switch
                {
                    ".jpg" or ".jpeg" => "image/jpeg",
                    ".png" => "image/png",
                    ".gif" => "image/gif",
                    _ => "application/octet-stream"
                };

                return PhysicalFile(filePath, contentType);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = $"获取文件失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filePath">文件相对路径</param>
        /// <returns>是否删除成功</returns>
        [HttpDelete("delete")]
        [Authorize]
        public async Task<IActionResult> Delete([FromQuery] string filePath)
        {
            try
            {
                var result = await _fileService.DeleteFileAsync(filePath);
                if (result)
                {
                    return Ok(new { message = "文件删除成功" });
                }
                return NotFound(new { message = "文件不存在" });
            }
            catch (Exception)
            {
                return StatusCode(500, new { message = "文件删除失败" });
            }
        }
    }
} 